package com.casic.ops.runner.pipeline.node;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.casic.ops.dao.pipeline.PipelineLoggerDAO;
import com.casic.ops.entity.domain.pipeline.PipelineLoggerDO;
import com.casic.ops.entity.dto.pipeline.datastructure.context.DefaultResult;
import com.casic.ops.entity.dto.pipeline.datastructure.context.Result;
import com.casic.ops.entity.dto.pipeline.datastructure.enums.NodeEnum;
import com.casic.ops.entity.dto.pipeline.datastructure.enums.NodeExecuteStatus;
import com.casic.ops.entity.dto.pipeline.datastructure.enums.PipelineBuildResultEnum;
import com.casic.ops.entity.dto.pipeline.datastructure.executecontext.PipelineExecuteContext;
import com.casic.ops.entity.dto.pipeline.datastructure.graph.Nodes;
import com.casic.ops.service.api.pipeline.PipelineLoggerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;



/**
 * 流水线结束节点,可以做一些后置如清理工作空间的工作
 * @author cww
 * @date 2022/6/20
 */
@Service
@Slf4j
public class EndExecutableNode implements ExecutableNode {

    @Resource
    private PipelineLoggerService pipelineLoggerService;

    @Override
    public Result execute(PipelineExecuteContext executeContext,String nodeUuid) {
        log.info(getName());
        try {
            Thread.sleep(5000);
            PipelineExecuteContext context = executeContext;
            List<Nodes> nodes = context.getNodes();
            nodes.forEach(v-> {
                if(NodeEnum.END.getName().equals(v.getName())){
                    v.refreshStatus(NodeExecuteStatus.SUCCESS);
                }
            });
            context.getGraph().setNodes(nodes);
            PipelineLoggerDO logger = context.getLogger();
            logger.setExecuteEndTime(new Date());
            logger.setGraphContent(JSON.toJSONString(context.getGraph()));
            logger.setFinalStatus(PipelineBuildResultEnum.SUCCESS.getDesc());
            pipelineLoggerService.updateByLoggerDO(logger);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        DefaultResult defaultResult= new DefaultResult();
        defaultResult.add("status",0);
        return defaultResult;
    }
    /**
     * 此方法返回的name是和pipeline_node_template里面节点的name是对应的，如果要修改，请同时去数据库里面，把对应的一条数据的name也改成一致的
     * @return
     */
    @Override
    public String getName() {
        return "END";
    }
}
